package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.PropertyDAO;
import it.unibz.ti2.internetPizzeria.entities.Property;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Retrieves all configuration properties from database and passes them to
 * manageConfiguration.jsp page. Updates changed properties.
 */
public class ManageConfiguration extends HttpServlet{

	private static final long serialVersionUID = -1784098047129772579L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PropertyDAO propertyDAO = null;
		try {
			propertyDAO = new PropertyDAO();
			propertyDAO.openSession();
			List<Property> properties = propertyDAO.getAllProperties(true);
			request.setAttribute("properties", properties);
			
			properties = propertyDAO.getAllProperties();
			for (Property property : properties) {
				String parameter = request.getParameter(property.getKey());
				if (parameter != null){
					if (!parameter.equals(property.getValue())){
						property.setValue(parameter);
						propertyDAO.update(property);
					}
				}
			}
			
			ServletUtil.redirect(request, response, "/manageConfiguration.jsp");
			
		} catch (Exception ex) {			
			ex.printStackTrace();
		} finally {
			if (propertyDAO != null){
				propertyDAO.closeSession();
			}
		}
	}
}
